package org.example.back.controller.user;

import org.example.back.entity.user.UserProfile;
import org.example.back.service.user.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;

@RestController
@RequestMapping("/userProfile")
public class UserProfileController {

    @Autowired
    private UserProfileService userProfileService;

    // 保存用户资料
    @PostMapping("/save")
    public String saveUserProfile(@RequestBody UserProfile userProfile, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return "请先登录";
        }
        userProfile.setUserId(userId);
        userProfileService.saveUserProfile(userProfile);
        return "用户资料保存成功";
    }

    // 查询用户资料 - 不再通过 URL 传 userId，而从 Session 获取
    @GetMapping("/get")
    public UserProfile getUserProfile(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return null;  // 也可以抛异常或返回错误消息
        }
        return userProfileService.getUserProfileByUserId(userId);
    }

    // 更新用户资料 - 从 Session 取 userId，防止越权
    @PutMapping("/update")
    public String updateUserProfile(@RequestBody UserProfile userProfile, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return "请先登录";
        }
        if (!userId.equals(userProfile.getUserId())) {
            return "非法操作";
        }
        userProfileService.updateUserProfile(userProfile);
        return "用户资料更新成功";
    }
}
